package com.rocky.server.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;


public class DBAdapter {
	private static Logger logger = Logger.getLogger(DBAdapter.class);
	public Connection con = null;
	public Statement stmt = null;
	public ResultSet rs = null;
	static JdbcConnection connection;
	
	
	public DBAdapter(){		
		connection = new JdbcConnection();
	}
	
	public void closeConnect(){
		if(connection!=null){
			try {
				stmt.close();
				con.close();
			} catch (SQLException e) {
				logger.error(e.toString());
			}
		}
	}
	
	public void open_new_connect(){
		System.out.println("open new connect !");
		connection = new JdbcConnection();
	}
	
	/**
	 * 开启事务
	 * */
	public void startTransaction(){
		System.out.println("startTransaction()	");
		try {
			if(con!=null){
				con.setAutoCommit(false);
			}
		} catch (SQLException e) {
			logger.error(e.toString());
		}
	}
	
	/**
	 * 提交事务
	 * */
	public void commitTransaction(){
		
		System.out.println("commitTransaction()	");
		try {
			if(con!=null){
				con.commit();
			}
		} catch (SQLException e) {
			logger.error(e.toString());
		}
	}
	
	/**
	 * 回滚事务
	 * */
	public void rollTransaction(){
		
		System.out.println("rollTransaction()	");
		try {
			if(con!=null){
				con.rollback();
			}
		} catch (SQLException e) {
			logger.error(e.toString());
		}
	}
	
	private class JdbcConnection{

		private String user = "root";
		//private String password = "p@ssw0rd";
		private String password = "p@ssw0rd9527";
		//String url = "jdbc:mysql://127.0.0.1:3306/chat?useUnicode=true&characterEncoding=UTF-8";
		String url = "jdbc:mysql://127.0.0.1:3308/chat?useUnicode=true&characterEncoding=UTF-8";
		String driver = "org.gjt.mm.mysql.Driver";
		
		public JdbcConnection() {
			try {
				Class.forName(driver);
				con = DriverManager.getConnection(url, user, password);	
				stmt = con.createStatement();
			} catch (Exception e) {
				logger.error(e.toString());
			}
		}
	}
	
	
    
}
